<template>
  <div>
    <VAceEditor
      v-model:value="localContent"
      :class="className"
      :width="'100%'"
      :lang="mode"
      :placeholder="placeholder"
      :theme="theme"
      :style="{ height: height }"
      :options="mergedOptions"
      @change="updateContent"
    />
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { VAceEditor } from 'vue3-ace-editor'
import 'ace-builds/src-noconflict/snippets/java'
import 'ace-builds/src-noconflict/mode-java'
import 'ace-builds/src-noconflict/mode-sql'
import 'ace-builds/src-noconflict/mode-json'
import 'ace-builds/src-noconflict/snippets/sql'
import 'ace-builds/src-noconflict/snippets/json'
import 'ace-builds/src-noconflict/theme-solarized_dark'
import 'ace-builds/src-noconflict/theme-textmate'
import 'ace-builds/src-noconflict/ext-language_tools'

const props = defineProps({
  content: {
    type: String,
    required: true
  },
  placeholder: {
    type: String,
    default: '请输入内容',
    required: false
  },
  theme: {
    type: String,
    default: 'textmate'
  },
  options: {
    type: Object,
    default: () => ({})
  },
  className: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '800px'
  },
  mode: {
    type: String,
    default: 'json'
  }
})

const emit = defineEmits(['change'])
const localContent = ref('')

// 更新时触发自定义事件
function updateContent(e) {
  emit('change', localContent.value)
}

const defaultOptions = {
  highlightActiveLine: false,
  enableBasicAutocompletion: true,
  enableLiveAutocompletion: true,
  enableSnippets: true,
  showGutter: true,
  showLineNumbers: true,
  displayIndentGuides: false,
  showPrintMargin: false,
  fontSize: '14px',
  useWorker: false
}

const mergedOptions = computed(() => ({
  ...defaultOptions,
  ...props.options
}))

onMounted(() => {
  watch(
    () => props.content,
    (newContent) => {
      localContent.value = newContent
    },
    { immediate: true } // 立即执行一次，相当于初始化
  )
})
</script>

<style scoped></style>
